<?php

namespace common\jobs\handle;

use Yii;
use yii\db\Exception;
use common\models\member\MemberAccount;
use common\models\member\MemberCashout;
use common\models\member\MemberCashoutLog;
use common\models\member\MemberCashoutOrder;

/**
 * 佣金提现自动审核任务处理
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 * @property MemberCashout|null $model
 */
class CashoutAuditHandle extends \common\jobs\base\BaseJobHandleModel {

    /**
     * @var integer 提现申请记录ID
     */
    public $cashout_id = null;

    /**
     * @var MemberCashout|null 提现申请
     */
    public $_model = null;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['cashout_id'], 'required'],
            [['cashout_id'], 'integer'],
            [['cashout_id'], 'validateApply'],
        ];
    }

    /**
     * 校验提现申请信息
     *
     * @param string $attribute the attribute currently being validated
     */
    public function validateApply($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = MemberCashout::findOne($this->$attribute);
        if (!$model) {
            return $this->addError($attribute, '【' . $this->$attribute . '】申请不存在！');
        }
        if (!$model->getCanAudit()) {
            return $this->addError($attribute, '【' . $this->$attribute . '】申请状态已变更不能重复审核！');
        }
        $this->_model = $model;
    }

    /**
     * 获取提现申请信息
     *
     * @return MemberCashout|null
     */
    public function getModel() {
        return $this->_model;
    }

    /**
     * 执行申请审核
     * @inheritdoc
     */
    public function save() {
        Yii::error('CashoutAuditHandle starting...');
        if (!$this->validate()) {
            Yii::error('申请自动审核操作失败');
            Yii::error($this->getErrors());
            return $this->dumpError('申请自动审核操作失败');
        }
        Yii::error('CashoutAuditHandle is validated.');
        //获取提现申请信息
        $apply = $this->getModel();
        Yii::error([
            'apply attributes' => $apply->attributes
        ]);
        //创建基础审核日志
        $log = new MemberCashoutLog();
        $log->attributes = [
            'cashout_id' => $apply->id,
            'member_id' => $apply->member_id,
            'user_id' => $apply->user_id,
            'auditer_id' => 0,
            'status' => MemberCashoutLog::STATUS_ACTIVE,
        ];
        //开启事务保存
        $transaction = Yii::$app->db->beginTransaction();
        try {
            //执行审核
            $this->audit($apply, $log);
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            Yii::error($e->getMessage());
            $this->dumpRetryError($e->getMessage());
        }
        //@todo 执行成功后消除任务队列
        return $this->dumpSuccess([
            'CashoutId' => $apply->id,
            'Attributes' => $apply->attributes,
            'Message' => '提现申请审核完成！',
        ]);
    }

    /**
     * 审核操作
     * @param MemberCashout $apply
     * @param MemberCashoutLog $log
     * {@inheritdoc}
     */
    protected function audit($apply, $log) {
        //1、先设置审核状态审核中
        $apply->status = MemberCashout::STATUS_AUDITING;
        if (!$apply->save()) {
            throw new Exception($apply->getErrorMsg());
        }
        //1.1、创建审核中日志
        $auditingLog = clone $log;
        $auditingLog->mark = '系统自动审核，开始审核';
        if (!$auditingLog->save()) {
            throw new Exception($auditingLog->getErrorMsg());
        }
        //2、开始验证申请信息
        $auditStatus = MemberCashout::STATUS_REFUSE;
        $mark = null;
        /* @var $account MemberAccount */
        $account = $apply->account;
        $applyAmount = $apply->value - $apply->recharge;
        //2、验证提现申请的用户信息
        if (!$apply->validateOpenid()) {
            //2.1、审核拒绝不通过
            $mark = '申请的用户OPENID与系统用户的OPENID不一致';
        } elseif ($account->status !== MemberAccount::STATUS_ACTIVE) {
            $mark = '账户状态异常，不能进行提现！';
        } elseif ($apply->value < MemberAccount::WITHDRAW_AMOUNT_LIMIT) {
            $mark = '申请金额不足';
        } elseif ($account->current < $applyAmount) {
            $mark = '账户余额不足！';
        } else {
            $mark = '提现申请审核通过！';
            $auditStatus = MemberCashout::STATUS_ACTIVE;
        }
        $apply->status = $auditStatus;
        if (!$apply->save()) {
            throw new Exception($apply->getErrorMsg());
        }
        $auditedLog = clone $log;
        $auditedLog->mark = $mark;
        if (!$auditedLog->save()) {
            throw new Exception($auditedLog->getErrorMsg());
        }
        //未通过审核直接返回
        if ($auditStatus !== MemberCashout::STATUS_ACTIVE) {
            return;
        }
        //通过审核后创建提现订单
        $order = MemberCashoutOrder::findOrNew([
            'cashout_id' => $apply->id
        ]);
        //已付款的订单直接返回
        if (!$order->isNewRecord && $order->isPaid) {
            return;
        }
        $order->paymode = MemberCashoutOrder::PAYMODE_WECHAT;
        $order->user_id = $apply->user_id;
        if ($order->isNewRecord || $apply->value !== $order->amount || $apply->recharge !== $order->recharge) {
            $order->generateNo();
        }
        $order->setAttributes([
            'member_id' => $apply->member_id,
            'amount' => $apply->value,
            'recharge' => $apply->recharge,
            'pay' => $apply->value - $apply->recharge,
            'expired_at' => time() + 15 * 86400,
            'description' => '咸阳海泉湾达人佣金提现',
            'status' => MemberCashoutOrder::STATUS_DEFAULT,
        ]);
        if (!$order->save()) {
            throw new Exception($order->getErrorMsg());
        }
    }

}
